<script setup>
import {reactive, ref, onMounted, watch, onBeforeMount, onBeforeUnmount, onUnmounted} from "vue";
import {useRouter, onBeforeRouteLeave, onBeforeRouteUpdate} from "vue-router";
import {ElMessage} from "element-plus";
import userStore from "../../store/user.js";
import {ChatRound, Picture} from "@element-plus/icons-vue";
import {socket} from "../../util/websocket.js";
import svg from '../../../public/聊天.svg'

const router = useRouter()
const user = userStore()
const emojis = ref(['😂', '🙏', '😄', '😏', '😇', '😅', '😌', '😘', '😍', '🤓', '😜', '😎', '😊', '😳', '🙄', '😱', '😒', '😔', '😷', '👿', '🤗', '😩', '😤', '😣', '😰', '😴', '😬', '😭', '👻', '👍', '✌️', '👉', '👀', '🐶', '🐷', '😹', '⚡️', '🔥', '🌈', '🍏', '⚽️', '❤️', '🇨🇳'])
const input = ref('')
const form = JSON.parse(sessionStorage.getItem('userInfo'))

// // 用户离开路由时清除sessionStorage
// onBeforeRouteLeave(() => {
//   sessionStorage.removeItem('userInfo')
// })
// 获取用户列表
console.log(socket)
const userList = ref([])
socket.emit('list')
// 这是一个实时更新列表的方法
const Listener = (data) => {
  const myUser = data.find(item => item.username === form.username);

  // 将自己的信息放在列表的第一个位置
  if (myUser) {
    const myIndex = data.indexOf(myUser);
    data.splice(myIndex, 1); // 移除自己的信息
    data.unshift(myUser); // 将自己的信息放在第一个位置
  }

  // 更新状态
  userList.value = data;
};

socket.on('userList', function (data) {
  Listener(data);
});

// --------------------------------------------------------------------------
// 公共列表数据
const AllMsg = ref([])

// 本人数据
socket.on('send', function (msg) {
  // 收集服务端传来的本人的消息数据
  AllMsg.value.push(msg)

})

// 其他人数据
socket.on('other', function (msg) {
  if (msg.username === form.username) {
    return
  }
  AllMsg.value.push(msg)
})

// 图片数据
socket.on('receiveImage', function (msg) {
  AllMsg.value.push(msg)
})

// 进入群数据
socket.on('new-user', function (msg) {
  AllMsg.value.push(msg)
})

// ------------------------------------------------------------------------------
// 点击发送按钮
const handleSend = () => {
  if (!form || !user.userInfo) {
    ElMessage({
      message: '请求超时，请重新登录！',
      type: 'error'
    })
    router.push('/login')
    return
  }
  if (!input.value) {
    ElMessage({
      message: '请输入内容',
      type: 'error'
    })
    return
  }
  // 把数据传给服务端
  socket.emit('my_message', {
    ...form,
    content: input.value,
    time: new Date().toLocaleString()
  })
  input.value = ''
}

// 添加表情包
const handleEmoji = (e) => {
  input.value += e.target.innerText
}

// 滚动到底部
const messageContainer = ref(null)
const scrollToBottom = () => {
  const lastMessageElement = messageContainer.value?.lastElementChild;
  if (lastMessageElement) {
    lastMessageElement.scrollIntoView({
      behavior: "smooth",
      block: "end",
    });
  }
}

// 监听消息列表的变化，自动滚动到最新消息
watch(AllMsg, (newVal, oldVal) => {
  let newCode = newVal.at(-1).code
  if (newCode === 200 || newCode === 202) {
    ElMessage({
      message: '新消息来了',
      type: 'success'
    })
  }
  scrollToBottom();
}, {deep: true});

// 上传图片
const fileInput = ref(null);
const dialogTableVisible = ref(false);
const toggleFileInput = () => {
  fileInput.value.click();
};

const handleFileChange = (event) => {
  const files = event.target.files;
  if (files && files.length > 0) {
    const file = files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e) => {
      socket.emit('sendImage', {
        ...form,
        img: e.target.result,
        time: new Date().toLocaleString()
      })
    };
  }
};

// 点击图片显示对话框
const preview_img = ref(null);
const handleImage = (img) => {
  dialogTableVisible.value = true;
  preview_img.value = img;
};

// 在组件卸载时移除监听器
onUnmounted(() => {
  socket.close()
});
</script>

<template>
  <div class="container">
    <div class="sider">
      <div class="title">
       <div style="display: flex;align-content: center;margin-left:10px;width: 200px;">
         <img :src="svg" style="width: 40px;height: 40px;" alt="HappyChat">
         <p style="font-size: 25px;font-weight: bold;color: white;margin-left: 10px">HappyChat</p>
       </div>

        <div class="user_list">
          <div class="addUser">
            <p>在线列表</p>
          </div>

          <div class="list">
            <div v-for="(item,index) in userList" :key="index"
                 :class="form.username === item.username ? 'user active' : 'user'">
              <el-avatar
                  :size="70"
                  :src="item.avatar"/>

              <div class="info">
                <p>{{ item.username }}</p>
                <p :class="item.username === form.username ? 'active' : ''">{{
                    item.detail
                  }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="main">

      <!-- 聊天框-->
      <div class="chat-box">
        <div class="chat_content" ref="messageContainer">
          <div v-for="item in AllMsg" :key="item">
            <!-- 用户进入退出时的消息-->
            <div class="message_item" v-if="item.code===200">
              <div class="item0">
                <p>{{ item.message }}</p>
              </div>
            </div>
            <!-- 自己发的消息-->
            <div class="message_item" v-if="item.code===201">
              <div class="item1">
                <div class="all_content">
                  <div class="avatar">
                    <div class="avatar_item">
                      <el-avatar :size="40" :src="item.avatar"/>
                    </div>
                  </div>
                  <div class="father_content">
                    <div class="content">
                      <span>{{ item.content }}</span>
                      <img :src="item.img" alt="" style="width: 200px;height: 100px;cursor: pointer" v-if="item.img"
                           @click="handleImage(item.img)">
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 别人发的消息-->
            <div class="message_item" v-if="item.code===202">
              <div class="item2">
                <div class="all_content">
                  <div class="avatar">
                    <div class="avatar_item">
                      <el-avatar :size="40" :src="item.avatar"/>
                      <p>{{ item.username }}</p>
                    </div>
                  </div>
                  <div class="father_content">
                    <div class="content">
                      <span>{{ item.content }}</span>
                      <img :src="item.img" alt="" style="width: 200px;height: 100px;cursor: pointer" v-if="item.img"
                           @click="handleImage(item.img)">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 图片预览-->
      <el-dialog v-model="dialogTableVisible" width="800" :show-close="false" style="background: transparent">
        <img :src="preview_img" alt="" style="width: 100%;">
      </el-dialog>
      <!-- 输入框-->
      <div class="chat-input">
        <div class="emoji">
          <el-popover placement="top" :width="500"
                      trigger="hover"
                      popper-style="height:300px;overflow-y:scroll;border-radius:10px;">
            <template #reference>
              <el-button :icon="ChatRound" circle/>
            </template>
            <el-row :gutter="20">
              <el-col :span="4" v-for="(item,index) in emojis" :key="index">
                <p @click="handleEmoji"
                   style="font-size: 40px;display: flex;cursor:pointer;justify-content: center;justify-items: center;">
                  {{ item }}</p>
              </el-col>
            </el-row>
          </el-popover>
        </div>
        <div class="picture">
          <el-button :icon="Picture" circle @click="toggleFileInput">
            <template #default>
              <input type="file" ref="fileInput" @change="handleFileChange" accept="image/*" multiple
                     style="display: none"/>
            </template>
          </el-button>
        </div>
        <div class="input-send">
          <input type="text" class="form-control" v-model="input" aria-describedby="emailHelp"
                 @keypress.enter="handleSend"/>
        </div>

        <div class="button-send">
          <button class="btn btn-secondary" @click="handleSend">发送</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">

.item {
  margin-top: 10px;
  margin-right: 30px;
}

.active {
  background-color: #118bfa !important;
  color: white !important;
}

.container {
  width: 2205px;
  height: 700px;
  border-radius: 30px;
  display: flex;
  margin: 50px auto;
  justify-content: end;
  justify-items: center;
  align-items: center;
  background-color: #3a425e;
  animation: wechat 4s ease-in-out infinite;

  @keyframes wechat {
    0% {
      box-shadow: 0px 0px 10px 5px rgb(140, 138, 138);
    }
    50% {
      box-shadow: 0px 0px 10px 7px rgb(114, 111, 111);
    }
    100% {
      box-shadow: 0px 0px 10px 6px rgb(140, 138, 138);
    }
  }

  .sider {
    width: 500px;
    border-radius: 20px 0 0 20px;
    height: 100%;
    display: flex;
    flex-direction: column;

    .title {
      width: 100%;
      margin-top: 40px;

      h4 {
        color: white;
        font-weight: bold;
        margin-left: 20px;
        font-size: 20px;
      }
    }

    .user_list {
      width: 100%;
      margin-top: 80px;
      height: 500px;
      overflow-y: scroll;

      .addUser {
        width: 80%;
        height: 50px;
        display: flex;
        justify-content: space-between;

        p {
          font-size: 20px;
          color: white;
        }

        .el-button {
          width: 25px;
          font-size: 20px;
          height: 25px;
        }

      }

      .list {
        width: 100%;
        height: 400px;
        display: flex;
        flex-direction: column;
        align-items: center;

        .user {
          cursor: pointer;
          width: 80%;
          height: 90px;
          padding: 10px;
          display: flex;
          background-color: #293550;
          margin-bottom: 10px;
          border-radius: 10px;
          justify-content: space-evenly;

          .info {
            width: 80%;
            height: 70px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            margin-left: 10px;

            p {
              color: white;
              font-size: 18px;
              margin: 5px;
            }

            p:nth-child(2) {
              color: #8d8585;
              font-size: 14px;
            }
          }
        }
      }
    }
  }

  .main {
    border-radius: 20px;
    margin-right: 20px;
    width: 1200px;
    height: 90%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    background-color: #313746;

    .chat-box {
      width: 100%;
      height: 85%;
      overflow-x: hidden;
      overflow-y: scroll;
      display: flex;
      padding: 20px;

      .chat_content {
        width: 100%;

        .message_item {
          width: 100%;
          margin-bottom: 20px;

          .item0 {
            width: 200px;
            text-align: center;
            height: 30px;
            color: #cccccc;
            font-size: 15px;
            margin: 0 auto;
          }

          .item1 {
            width: 100%;
            display: flex;
            justify-content: flex-end;

            .all_content {
              width: 500px;

              .avatar {
                width: 100%;
                height: 40px;
                display: flex;
                justify-content: flex-end;
                margin-right: 5px;
              }

              .father_content {
                width: fit-content;
                float: right;
                margin-right: 10px;

                .content {
                  display: flex;
                  justify-content: flex-end;
                  margin-top: 5px;
                  height: auto;
                  width: fit-content;
                  color: #d5dbec;
                  font-size: 17px;
                  font-weight: bold;
                  background-color: #438b07;
                  border-radius: 7px;
                  padding: 10px;
                }
              }
            }

          }

          .item2 {
            width: 100%;
            display: flex;
            justify-content: flex-start;

            .all_content {
              width: 500px;

              .avatar {
                width: 100%;
                height: 40px;
                display: flex;
                justify-content: flex-start;
                margin-left: 5px;

                .avatar_item {
                  width: 100px;
                  align-items: center;
                  display: flex;

                  p {
                    color: white;
                    margin-left: 10px;
                    margin-top: 15px;
                    line-height: 40px;
                    font-size: 20px;
                    height: 40px;
                  }
                }
              }

              .father_content {
                width: fit-content;
                float: left;
                margin-left: 20px;

                .content {
                  display: flex;
                  justify-content: flex-start;
                  margin-top: 5px;
                  height: auto;
                  width: fit-content;
                  color: #d5dbec;
                  font-size: 17px;
                  font-weight: bold;
                  background-color: #787a76;
                  border-radius: 7px;
                  padding: 10px;
                }
              }
            }
          }
        }
      }
    }

    .chat-input {
      width: 100%;
      height: 10%;
      display: flex;
      justify-content: space-around;

      .emoji {
        width: 5%;
        height: 80%;
        display: flex;
        justify-content: center;
        align-items: center;

        .el-button {
          width: 40px;
          height: 40px;
          font-size: 25px;
        }

        .emoji_child {
          width: 90%;
          height: auto;
          display: flex;
          flex-wrap: wrap;
        }
      }

      .picture {
        width: 5%;
        height: 80%;
        display: flex;
        justify-content: center;
        align-items: center;

        .el-button {
          width: 40px;
          height: 40px;
          font-size: 25px;
        }
      }

      .input-send {
        width: 75%;
        height: 80%;

        input {
          height: 100%;
          background-color: #313746;
          border: 1px solid #434850;
          color: white;
        }
      }

      .button-send {
        width: 10%;
        height: 80%;

        button {
          width: 100%;
          height: 100%;
          font-size: 20px;
        }
      }
    }
  }
}

</style>